﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SeDuce.Model;
using SeDuce.BLL;
using System.Data;
using SeDuce.Utility;
using System.IO;

public partial class Management_News_Modify : PageBase
{
    List<News> news = new List<News>();

    Lazy_Yu<NewsBLL> lazyNewsBLL = new Lazy_Yu<NewsBLL>(() => new NewsBLL());
    public NewsBLL LazyNewsBLL
    {
        get { return this.lazyNewsBLL.Value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dtNews = this.LazyNewsBLL.GetNewsByID(this.GetQueryString("NewsID", false).ToInt());
            if (dtNews.Rows.Count > 0)
            {
                News news = dtNews.ToList<News>().SingleOrDefault();
                this.lblID.Text = news.ID.ToString();
                this.txtName.Text = news.Title;
                this.txtContent.Value = news.ContentText;
                this.DropDownListBind(this.ddlNewsTypes, this.LazyNewsBLL.GetNewsTypes(), "TypeName", "ID");
                this.DropDownListFixByValue(this.ddlNewsTypes, news.TypeID.ToString());

                this.DropDownListFixByValue(this.ddlSeq, news.Seq.ToString());

                this.chkIsInGallery.Checked = news.IsInGallery;
                this.DropDownListFixByValue(this.ddlIsHeadline, news.IsHeadline.ToString());

                this.AddAttributes("OldLogoPath", Server.MapPath(news.Pic));
                this.AddAttributes("OldLogoFilename", news.Pic);
            }
        }
    }
    protected void lbtnSave_Click(object sender, EventArgs e)
    {
        if (Session["file_info"] != null)
        {
            if (!System.IO.Directory.Exists(Server.MapPath(Misc.filepath)))
            {
                System.IO.Directory.CreateDirectory(Server.MapPath(Misc.filepath));
            }
            if (!string.IsNullOrEmpty(this.GetAttributes("OldLogoPath")))
            {
                if (File.Exists(this.GetAttributes("OldLogoPath")))
                {
                    File.Delete(this.GetAttributes("OldLogoPath"));
                }
            }
            List<string> file_list_to_delete = new List<string>();
            try
            {
                List<Thumbnail> thumbnails = Session["file_info"] as List<Thumbnail>;
                ImageHelp imgHelper = new ImageHelp();

                string UploadPath = Server.MapPath(Misc.news_filepath);
                if (!System.IO.Directory.Exists(UploadPath))
                {
                    System.IO.Directory.CreateDirectory(UploadPath);
                }

                foreach (Thumbnail img in thumbnails)
                {
                    string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Guid.NewGuid().ToString().Replace("-", "");
                    string fullfilename = filename + Path.GetExtension(img.ID).ToLower();
                    file_list_to_delete.Add(Misc.news_filepath + "/" + fullfilename);
                    FileStream fs = new FileStream(UploadPath + "/" + fullfilename, FileMode.Create);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(img.Data);
                    bw.Close();
                    fs.Close();

                    //watermark
                    //Utils.Watermark(UploadPath + "\\Temp_" + fullfilename, UploadPath + "\\" + fullfilename, Server.MapPath(Misc.watermark), "FULL");

                    news.Add(new News()
                    {
                        ID = this.lblID.Text.ToInt(),
                        Title = this.txtName.Text.Trim(),
                        ContentText = this.txtContent.Value.Trim(),
                        Pic = Misc.news_filepath + "/" + fullfilename,
                        UpdateDate = DateTime.Now,
                        Seq = this.ddlSeq.SelectedValue.ToInt(),
                        TypeID = this.ddlNewsTypes.SelectedValue.ToInt(),
                        IsInGallery = this.chkIsInGallery.Checked,
                        IsHeadline = this.ddlIsHeadline.SelectedValue.ToInt()
                    });

                    //替换老图片
                    this.AddAttributes("OldLogoPath", Server.MapPath(Misc.news_filepath + "/" + fullfilename));
                    this.AddAttributes("OldLogoFilename", Misc.news_filepath + "/" + fullfilename);
                }
                if (this.LazyNewsBLL.UpdateNews(news[0]))
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key3", "javascript:" + string.Format("alert('{0}');window.location.reload();", "操作成功!"), true);
                }
                else
                {
                    throw new Exception("保存时发生错误");
                }
            }
            catch (Exception ex)
            {
                foreach (string file in file_list_to_delete)
                {
                    if (File.Exists(Server.MapPath(file)))
                    {
                        File.Delete(Server.MapPath(file));
                    }
                }
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key4", "javascript:" + string.Format("alert('{0}');window.location.reload();", "保存时发生错误!请重试..."), true);
            }
            finally
            {
                Session.Remove("file_info");
            }
        }
        else
        {
            bool result = this.LazyNewsBLL.UpdateNews(new News()
            {
                ID = this.lblID.Text.ToInt(),
                Title = this.txtName.Text.Trim(),
                ContentText = this.txtContent.Value.Trim(),
                Pic = this.GetAttributes("OldLogoFilename"),
                UpdateDate = DateTime.Now,
                Seq = this.ddlSeq.SelectedValue.ToInt(),
                TypeID = this.ddlNewsTypes.SelectedValue.ToInt(),
                IsInGallery = this.chkIsInGallery.Checked,
                IsHeadline = this.ddlIsHeadline.SelectedValue.ToInt()
            });
            if (result)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key5", "javascript:" + string.Format("alert('{0}');window.location.reload();", "操作成功!"), true);
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key6", "javascript:" + string.Format("alert('{0}');window.location.reload();", "保存时发生错误!请重试..."), true);
            }
        }
    }
    protected void lbtnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("List.aspx");
    }
}